using System;
using System.Collections;
using System.Collections.Generic;
using Sirenix.OdinInspector;
using UnityEngine;

[Serializable]
public class RigidBodyMoveComponent : MoveComponent
{
    public Rigidbody rb;
    [Title("是否根据摇杆百分比控制移动")]
    public bool IsPercent;

    /// <summary>
    /// 朝着相机方向移动
    /// </summary>
    /// <param name="Inputdir"></param>
    /// <param name="InputPercent"></param>
    public void Move(Vector2 Inputdir, float InputPercent)
    {
        // 将屏幕空间的输入方向转换为世界空间的移动方向
        Vector3 cameraForward = Camera.main.transform.forward;
        Vector3 cameraRight = Camera.main.transform.right;

        // 忽略y轴，保持在水平面上移动
        cameraForward.y = 0;
        cameraRight.y = 0;
        cameraForward.Normalize();
        cameraRight.Normalize();

        // 计算世界空间中的移动方向
        Vector3 moveDirection = (cameraRight * Inputdir.x + cameraForward * Inputdir.y).normalized;

        Vector3 velocity = Vector3.zero;
        if (IsPercent)
        {
            velocity = moveDirection * MoveSpeed * InputPercent;
        }
        else
        {
            velocity = moveDirection * MoveSpeed;
        }
        // 设置移动速度
        rb.velocity = new Vector3(velocity.x, rb.velocity.y, velocity.z);

        // 计算水平速度并更新动画
        Vector3 horizontalVelocity = new Vector3(rb.velocity.x, 0, rb.velocity.z);
        IsMoving = horizontalVelocity.magnitude > 0.1f;

        // 只在移动时才改变朝向
        if (IsMoving)
        {
            entity.GetEcsComponent<RotationComponent>().RotateToDirection(horizontalVelocity);
        }

    }

    public void ClearVelocity()
    {
        rb.velocity = Vector3.zero;
    }
    
}
